package top.ligongzi.hrm.controller;

import top.ligongzi.hrm.service.IVerifyCodeService;
import top.ligongzi.hrm.util.AjaxResult;
import top.ligongzi.hrm.util.VerifyCodeUtils;
import top.ligongzi.hrm.vo.ImgCodeVo;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@RestController
@RequestMapping("/verifycode")
public class VerifyCodeController {

    @Autowired
    private IVerifyCodeService verifyCodeService;

    //====================================单体项目图片验证码==============================//
    @GetMapping("/img")
    public void imgCode(HttpServletResponse response, HttpSession session){
        try {
            //生成验证码
            String code = VerifyCodeUtils.generateVerifyCode(4);
            //存放session
            session.setAttribute("registerImgCode", code);

            //图片验证码
            ByteArrayOutputStream data = new ByteArrayOutputStream();
            VerifyCodeUtils.outputImage(200, 50, data, code);

            //把图片验证码响应给用户
            IOUtils.write(data.toByteArray(), response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @GetMapping("/img/xxx")
    public void imgCode(String code,HttpSession session){
        String codeSession = (String) session.getAttribute("registerImgCode");
        System.out.println(codeSession);
    }
    //====================================单体项目图片验证码==============================//


    @GetMapping("/imageCode/{key}") //所有要获取图片验证码都可以使用
    public String imgCode(@PathVariable("key")String key){

        return verifyCodeService.getImgCode(key);
    }

    //获取图片验证码
    @PostMapping("/sendRegSmsCode") //注册所专用
    public AjaxResult sendSmsCode(@RequestBody ImgCodeVo imgCodeVo){
        verifyCodeService.sendSmsCode(imgCodeVo);
        return AjaxResult.me();
    }
}
